package com.scidpro.util;

import java.io.File;
import java.io.IOException;

import org.scid.database.DataBase;

import android.app.Notification;
import android.app.NotificationManager;
import android.app.PendingIntent;
import android.content.Context;
import android.content.Intent;
import android.os.AsyncTask;
import android.os.Build;
import android.os.Environment;
import android.widget.RemoteViews;
import android.widget.Toast;

import com.scidpro.MyBooksListActivity;
import com.scidpro.R;
import com.scidpro.ScidAndroidActivity;
import com.scidpro.Tools;

public class DownloadBookTask extends AsyncTask<Void, Void, Integer> {

	public static int nextId = 0;

	public static interface DownloadHandler {

		public void publishProgress(int progress);

	}

	private static final int RESULT_OK = 0;
	private static final int RESULT_DOWNLOAD_ERROR = 1;
	private static final int RESULT_IMPOTING_PGN_TO_DB_ERROR = 2;
	private static final int RESULT_IO_EXCEPTION = 3;

	private int id;

	private Context context;
	private Book book;

	public DownloadBookTask(Context context, Book book) {
		this.id = nextId;
		nextId += 1;

		this.context = context;
		this.book = book;
	}

	@Override
	protected Integer doInBackground(Void... params) {
		sendNotification("LearnChess: downloading book", book.name, -1, false);

		try {
			String directory = Environment.getExternalStorageDirectory() + File.separator + ScidAndroidActivity.SCID_DIRECTORY;

			File f = Tools.downloadFile(book.url, new DownloadHandler() {
				@Override
				public void publishProgress(int progress) {
					sendNotification("LearnChess: downloading book", book.name, progress, false);
				}
			});

			File pgn = null;
			if (f != null) {
				pgn = Tools.unzip(directory, f, true);
			} else {
				return RESULT_DOWNLOAD_ERROR;
			}

			DataBase db = new DataBase();
			final String result = db.importPgn(pgn.getAbsolutePath());

			if (!"".equals(result)) {
				return RESULT_IMPOTING_PGN_TO_DB_ERROR;
			}
		} catch (IOException e) {
			return RESULT_IO_EXCEPTION;
		}

		return RESULT_OK;
	}

	@Override
	protected void onPostExecute(Integer result) {
		if (result != null) {
			switch (result) {
			case RESULT_OK:
				Toast.makeText(context, "Success", Toast.LENGTH_SHORT).show();
				sendNotification("LearnChess: downloading complete", book.name, "Successfully downloaded");
				break;
			case RESULT_DOWNLOAD_ERROR:
			case RESULT_IMPOTING_PGN_TO_DB_ERROR:
			case RESULT_IO_EXCEPTION:
			default:
				sendNotification("LearnChess: downloading failure", book.name, "Downloading problems");
				break;
			}
		} else {
			sendNotification("LearnChess: downloading failure", book.name, "Downloading problems");
		}
	}

	private NotificationManager notificationManager;

	private void sendNotification(String ticker, String title, int progress, boolean cancelable) {
		if (Build.VERSION.SDK_INT < Build.VERSION_CODES.HONEYCOMB) {
			sendNotificationOld(ticker, title, progress, cancelable);
		} else {
			sendNotificationModern(ticker, title, progress, cancelable);
		}
	}

	private void sendNotificationModern(String ticker, String title, int progress, boolean cancelable) {
		Notification notification = new Notification();

		notification.icon = R.drawable.icon;
		notification.tickerText = ticker;
		notification.when = System.currentTimeMillis();
		notification.when = System.currentTimeMillis();

		if (cancelable) {
			notification.flags = notification.flags | Notification.FLAG_AUTO_CANCEL;
		} else {
			notification.flags = notification.flags | Notification.FLAG_ONGOING_EVENT;
		}

		notification.contentIntent = PendingIntent.getActivity(context, 0, new Intent(context, MyBooksListActivity.class), 0);

		notification.contentView = new RemoteViews(context.getPackageName(), R.layout.download_progress);
		notification.contentView.setImageViewResource(R.id.status_icon, R.drawable.icon);
		notification.contentView.setTextViewText(R.id.status_text, title);
		notification.contentView.setProgressBar(R.id.status_progress, 100, progress, progress < 0);

		if (notificationManager == null) {
			notificationManager = (NotificationManager) context.getSystemService(Context.NOTIFICATION_SERVICE);
		}
		notificationManager.notify(id, notification);
	}

	private void sendNotificationOld(String ticker, String title, int progress, boolean cancelable) {
		Notification notification = new Notification();

		notification.icon = R.drawable.icon;
		notification.tickerText = ticker;
		notification.when = System.currentTimeMillis();

		notification.flags = notification.flags | Notification.FLAG_ONGOING_EVENT;

		if (progress < 0)
			progress = 0;

		notification.setLatestEventInfo(context, title, "Downloading: " + progress + "%", PendingIntent.getActivity(context, 0, new Intent(context, MyBooksListActivity.class), 0));

		if (notificationManager == null) {
			notificationManager = (NotificationManager) context.getSystemService(Context.NOTIFICATION_SERVICE);
		}
		notificationManager.notify(id, notification);
	}

	private void sendNotification(String ticker, String title, String text) {
		Notification notification = new Notification();

		notification.icon = R.drawable.icon;
		notification.tickerText = ticker;
		notification.when = System.currentTimeMillis();

		notification.flags = notification.flags | Notification.FLAG_AUTO_CANCEL;

		notification.setLatestEventInfo(context, title, text, PendingIntent.getActivity(context, 0, new Intent(context, MyBooksListActivity.class), 0));

		if (notificationManager == null) {
			notificationManager = (NotificationManager) context.getSystemService(Context.NOTIFICATION_SERVICE);
		}
		notificationManager.notify(id, notification);
	}

}
